// pages/appointment/appointment.js
import { 
  getTimeSlotsByDate, 
  getConsultantsByTimeSlot, 
  submitAppointment 
} from '../../api/booking';

Page({
  data: {
    currentDate: '',
    currentTime: '',
    currentConsultant: '',
    currentConsultantId: null,
    currentMethod: '',
    content: '',
    wordCount: 0,
    isAgree: false,
    isToastShow: false,
    dateList: [],
    consultantList: [],
    isLoading: false,
    timeSlots: [],
    selectedTimeSlot: null,
    allConsultants: [],
    canSubmit: false,
    studentId: 0,
    isLoggedIn: false,
    loginCheckCompleted: false,
    needRefresh: false // 新增：标记是否需要刷新
  },
  
  onLoad(options) {
    const { consultantId, consultantName } = options || {};
    const dateList = this.generate6DaysDate();
    
    this.setData({
      dateList,
      currentDate: dateList[0].dateKey,
      currentConsultant: consultantName || '',
      currentConsultantId: consultantId ? Number(consultantId) : null,
    });
    
    this.checkLoginStatusSync();
    if (this.data.isLoggedIn) {
      this.loadPageData();
    }
  },

  // 新增：onShow 生命周期函数
  onShow() {
    // 如果标记需要刷新，则重新加载数据
    if (this.data.needRefresh) {
      this.setData({ 
        needRefresh: false,
        currentTime: '',
        currentConsultant: '',
        currentConsultantId: null,
        currentMethod: '',
        content: '',
        wordCount: 0,
        isAgree: false,
        selectedTimeSlot: null,
        consultantList: this.data.allConsultants
      });
      
      // 重新加载时间段和咨询师数据
      this.loadTimeSlots(this.data.currentDate);
      this.checkSubmitStatus();
    }
  },
  
  checkLoginStatusSync() {
    try {
      const studentInfo = wx.getStorageSync('studentInfo') || {};
      const userInfo = wx.getStorageSync('userInfo') || {};
      const loginInfo = wx.getStorageSync('loginInfo') || {};
      
      let studentId = Number(studentInfo.studentId) || Number(userInfo.studentId) || 
                      Number(loginInfo.studentId) || Number(studentInfo.id) || 
                      Number(userInfo.id) || Number(loginInfo.id) || 0;
      
      const isLoggedIn = studentId > 0;
      
      this.setData({
        studentId,
        isLoggedIn,
        loginCheckCompleted: true
      });
      
      if (!isLoggedIn) {
        wx.showModal({
          title: '登录状态异常',
          content: '请登录后再进行预约操作',
          showCancel: false,
          confirmText: '立即登录',
          success: (res) => {
            if (res.confirm) {
              wx.redirectTo({ 
                url: `/pages/logs/logs?redirect=${encodeURIComponent('/pages/appointment/appointment')}`
              });
            }
          }
        });
      }
    } catch (err) {
      console.error('登录状态校验失败：', err);
      this.setData({
        studentId: 0,
        isLoggedIn: false,
        loginCheckCompleted: true
      });
      wx.showToast({ title: '登录状态校验失败', icon: 'none' });
    }
  },
  
  async loadPageData() {
    this.setData({ isLoading: true });
    try {
      await this.getAllConsultants();
      // 加载默认日期的时间段
      await this.loadTimeSlots(this.data.currentDate);
      this.checkSubmitStatus();
    } catch (err) {
      console.error('初始化数据失败：', err);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },
  
  async getAllConsultants() {
    try {
      const { getAvailableConsultants } = require('../../api/consultant');
      const res = await getAvailableConsultants() || [];
      
      const allConsultants = res.map(item => ({
        id: Number(item.id || item.consultantId),
        name: item.name || item.consultantName || '',
        title: item.title || '',
        specialty: item.specialty || '',
        avatar: item.avatar || '/assets/img/index/头像.png',
        officeLocation: item.officeLocation || '',
        isAvailable: true
      }));
      
      this.setData({ allConsultants, consultantList: allConsultants });
    } catch (err) {
      console.error('获取咨询师失败：', err);
      // 备用咨询师数据
      const dbAllConsultants = [
        { id: 1, name: '李四', title: '教授', specialty: '情绪', avatar: 'http://test.yudao.iocoder.cn/20251103/头像_1762170313224.jpg', officeLocation: '办公楼319', isAvailable: true },
        { id: 2, name: '王五', title: '教师', specialty: '情感', avatar: 'http://test.yudao.iocoder.cn/20251103/123_1762170416284.jpeg', officeLocation: '办公楼318', isAvailable: true },
        { id: 3, name: '吴佳欣', title: '', specialty: '', avatar: '', officeLocation: '', isAvailable: true }
      ];
      this.setData({ allConsultants: dbAllConsultants, consultantList: dbAllConsultants });
    }
  },
  
  // 根据日期获取时间段
  async loadTimeSlots(dateKey) {
    try {
      const formatDate = `${dateKey.slice(0,4)}-${dateKey.slice(4,6)}-${dateKey.slice(6,8)}`;
      
      const result = await getTimeSlotsByDate({ date: formatDate });
      
      if (result && result.length > 0) {
        const timeSlots = result.map(slot => {
          // 根据接口返回的时间段格式进行处理
          let timeRange;
          if (slot.timeSlots) {
            timeRange = slot.timeSlots;
          } else if (slot.startTime && slot.endTime) {
            timeRange = `${this.formatTime(slot.startTime)}-${this.formatTime(slot.endTime)}`;
          } else {
            timeRange = '00:00:00-00:00:00';
          }
          
          return {
            timeRange: timeRange,
            original: timeRange,
            startTime: slot.startTime,
            endTime: slot.endTime,
            availableCount: slot.availableCount || 0,
            maxAppOnInternet: slot.maxAppOnInternet || 0
          };
        });
        
        this.setData({ timeSlots });
        console.log('获取到的时间段:', timeSlots);
      } else {
        // 如果没有时间段数据，显示空
        this.setData({ timeSlots: [] });
        wx.showToast({ title: '该日期暂无可用时段', icon: 'none' });
      }
    } catch (err) {
      console.error('获取时间段失败：', err);
      this.setData({ timeSlots: [] });
      wx.showToast({ title: '获取时段失败', icon: 'none' });
    }
  },
  
  // 格式化时间数组为字符串
  formatTime(timeArray) {
    if (!timeArray || !Array.isArray(timeArray)) return '00:00:00';
    const [hours, minutes, seconds = 0] = timeArray;
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  },
  
  // 根据时间段获取咨询师
  async loadConsultantsByTimeSlot() {
    try {
      const { currentDate, selectedTimeSlot } = this.data;
      if (!selectedTimeSlot) return;
      
      const formatDate = `${currentDate.slice(0,4)}-${currentDate.slice(4,6)}-${currentDate.slice(6,8)}`;
      
      // 修复时间分割逻辑 - 使用正确的分隔符
      let startTime, endTime;
      const timeString = selectedTimeSlot.original;
      
      if (timeString.includes('—')) {
        // 如果是长破折号
        [startTime, endTime] = timeString.split('—');
      } else if (timeString.includes('-')) {
        // 如果是短横线
        [startTime, endTime] = timeString.split('-');
      } else {
        console.error('未知的时间格式:', timeString);
        wx.showToast({ title: '时间格式错误', icon: 'none' });
        return;
      }
      
      // 清理并格式化时间 (确保是 HH:mm:ss 格式)
      startTime = this.ensureTimeFormat(startTime.trim());
      endTime = this.ensureTimeFormat(endTime.trim());
      
      console.log('请求咨询师参数:', { date: formatDate, startTime, endTime });
      
      const result = await getConsultantsByTimeSlot({
        date: formatDate,
        startTime: startTime,
        endTime: endTime
      });
      
      if (result && result.length > 0) {
        const availableConsultants = result.map(consultant => ({
          id: Number(consultant.id || consultant.consultantId),
          name: consultant.name || consultant.consultantName || '',
          title: consultant.title || '',
          specialty: consultant.specialty || '',
          avatar: consultant.avatar || '/assets/img/index/头像.png',
          officeLocation: consultant.officeLocation || '',
          isAvailable: true
        }));
        
        this.setData({ consultantList: availableConsultants });
        console.log('获取到的咨询师:', availableConsultants);
      } else {
        this.setData({ consultantList: [] });
        wx.showToast({ title: '该时段暂无可用咨询师', icon: 'none' });
      }
    } catch (err) {
      console.error('获取咨询师失败：', err);
      // 出错时显示所有咨询师
      this.setData({ consultantList: this.data.allConsultants });
      wx.showToast({ title: '获取咨询师失败，显示全部', icon: 'none' });
    }
  },
  
  // 确保时间格式为 HH:mm:ss
  ensureTimeFormat(timeStr) {
    // 如果只有 HH:mm，添加 :00
    if (timeStr.match(/^\d{1,2}:\d{2}$/)) {
      return timeStr + ':00';
    }
    // 如果已经是 HH:mm:ss，直接返回
    if (timeStr.match(/^\d{1,2}:\d{2}:\d{2}$/)) {
      return timeStr;
    }
    // 其他格式返回默认值
    return '00:00:00';
  },
  
  // 转换时间段格式为 HH:mm-HH:mm
  convertTimeSlotFormat(timeSlot) {
    // 处理不同的分隔符
    let startTime, endTime;
    if (timeSlot.includes('—')) {
      [startTime, endTime] = timeSlot.split('—');
    } else if (timeSlot.includes('-')) {
      [startTime, endTime] = timeSlot.split('-');
    } else {
      return timeSlot; // 如果无法解析，返回原值
    }
    
    // 清理空格
    startTime = startTime.trim();
    endTime = endTime.trim();
    
    // 移除秒部分，只保留 HH:mm
    startTime = startTime.split(':').slice(0, 2).join(':');
    endTime = endTime.split(':').slice(0, 2).join(':');
    
    return `${startTime}-${endTime}`;
  },
  
  generate6DaysDate() {
    const dateList = [];
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    for (let i = 0; i < 6; i++) {
      const d = new Date();
      d.setDate(d.getDate() + i);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      dateList.push({
        dateKey: `${year}${month}${day}`,
        week: i === 0 ? '今天' : weeks[d.getDay()],
        day: `${month}-${day}`,
        formatDate: `${year}-${month}-${day}`
      });
    }
    return dateList;
  },
  
  async selectDate(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({ 
      currentDate: date,
      currentTime: '', // 清空已选时间
      selectedTimeSlot: null,
      consultantList: this.data.allConsultants // 重置咨询师列表
    }, async () => {
      // 加载新日期的时间段
      await this.loadTimeSlots(date);
      this.checkSubmitStatus();
    });
  },
  
  async selectTime(e) {
    const { original } = e.currentTarget.dataset;
    const selectedTimeSlot = this.data.timeSlots.find(slot => slot.original === original);
    
    if (!selectedTimeSlot) return;
    
    console.log('选择的时间段:', selectedTimeSlot);
    
    this.setData({
      currentTime: selectedTimeSlot.timeRange,
      selectedTimeSlot
    }, async () => {
      // 根据选择的时间段加载可用的咨询师
      await this.loadConsultantsByTimeSlot();
      this.checkSubmitStatus();
    });
  },
  
  selectConsultant(e) {
    const { id, name, isavailable } = e.currentTarget.dataset;
    if (!isavailable) return;
    
    this.setData({
      currentConsultant: name,
      currentConsultantId: Number(id)
    }, () => this.checkSubmitStatus());
  },
  
  selectMethod(e) {
    this.setData({ currentMethod: e.currentTarget.dataset.method }, () => this.checkSubmitStatus());
  },
  
  inputContent(e) {
    const content = e.detail.value;
    if (content.length > 300) return;
    this.setData({ content, wordCount: content.length }, () => this.checkSubmitStatus());
  },
  
  toggleAgree() {
    this.setData({ isAgree: !this.data.isAgree }, () => this.checkSubmitStatus());
  },
  
  checkSubmitStatus() {
    const { 
      currentDate, currentTime, currentConsultantId, 
      currentMethod, content, isAgree, isLoggedIn,
      loginCheckCompleted
    } = this.data;
    this.setData({
      canSubmit: loginCheckCompleted && isLoggedIn && !!currentDate && !!currentTime && 
                currentConsultantId !== null && !!currentMethod && !!content.trim() && isAgree
    });
  },
  
  async submitAppointment() {
    if (!this.data.canSubmit) {
      return wx.showToast({ title: '请完善所有预约信息', icon: 'none' });
    }
    
    const { 
      currentDate, currentConsultantId, currentMethod, 
      content, selectedTimeSlot, studentId 
    } = this.data;
    
    const consultDate = `${currentDate.slice(0,4)}-${currentDate.slice(4,6)}-${currentDate.slice(6,8)}`;
    
    if (studentId <= 0) {
      wx.showModal({
        title: '登录失效',
        content: '你的登录状态已失效，请重新登录',
        showCancel: false,
        confirmText: '立即登录',
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({ 
              url: `/pages/logs/logs?redirect=${encodeURIComponent('/pages/appointment/appointment')}`
            });
          }
        }
      });
      return;
    }
    
    if (!selectedTimeSlot) {
      return wx.showToast({ title: '请选择有效时段', icon: 'none' });
    }
    
    try {
      // 转换时间段格式为后端需要的格式 (HH:mm-HH:mm)
      const timeSlot = this.convertTimeSlotFormat(selectedTimeSlot.original);
      
      // 严格按照接口文档的格式
      const submitParams = {
        studentId: studentId,
        consultantId: currentConsultantId,
        consultDate: consultDate,
        timeSlot: timeSlot, // 格式: "09:00-09:50"
        consultType: currentMethod === '线下咨询' ? 1 : currentMethod === '电话咨询' ? 2 : 3,
        problemDesc: content.trim(),
        remark: '希望安排在安静的环境'
      };
      
      console.log('最终提交参数：', submitParams);
      
      const res = await submitAppointment(submitParams);
      
      if (res) {
        wx.showToast({ title: '预约成功', icon: 'success', duration: 2000 });
        setTimeout(() => {
          // 设置需要刷新的标记
          this.setData({ needRefresh: true });
          
          // 跳转到我的预约页面
          wx.navigateTo({
            url: '/pages/myBooking/myBooking',
          });
        }, 2000);
      } else {
        wx.showModal({
          title: '预约失败',
          content: `${res.msg || '该时段无可用排班'}，请尝试选择其他时段或咨询师`,
          showCancel: false,
          confirmText: '重新选择'
        });
      }
    } catch (err) {
      console.error('提交失败：', err);
      wx.showToast({ title: err.message || '网络异常，请重试', icon: 'none' });
    }
  },
  
  closeToast() {
    this.setData({ isToastShow: false });
    wx.navigateBack();
  },
  
  viewConsultant(e) {
    const { id, isavailable } = e.currentTarget.dataset;
    if (isavailable && id) {
      wx.navigateTo({ url: `/pages/teacherdetail/teacherdetail?id=${id}` });
    }
  },

  // 新增：手动刷新方法（可选）
  refreshPage() {
    this.setData({ 
      currentTime: '',
      currentConsultant: '',
      currentConsultantId: null,
      currentMethod: '',
      content: '',
      wordCount: 0,
      isAgree: false,
      selectedTimeSlot: null,
      consultantList: this.data.allConsultants,
      isLoading: true
    });

    // 重新加载数据
    this.loadTimeSlots(this.data.currentDate).then(() => {
      this.setData({ isLoading: false });
      this.checkSubmitStatus();
    });
  }
});